package com.example.ywj.toutiao.fragments;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.AnimationDrawable;
import android.nfc.NfcAdapter;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.ywj.toutiao.Attention1Activity;
import com.example.ywj.toutiao.Attention2Activity;
import com.example.ywj.toutiao.CommentListActivity;
import com.example.ywj.toutiao.HomePageActivity;
import com.example.ywj.toutiao.LikeListActivity;
import com.example.ywj.toutiao.LoginActivity;
import com.example.ywj.toutiao.MainActivity;
import com.example.ywj.toutiao.PasswordActivity;
import com.example.ywj.toutiao.SaveListActivity;
import com.example.ywj.toutiao.bean.Comment;
import com.example.ywj.toutiao.bean.Item;

import com.example.ywj.toutiao.R;
import com.example.ywj.toutiao.bean.News;
import com.example.ywj.toutiao.bean.User;
import com.example.ywj.toutiao.utils.Constant;
import com.example.ywj.toutiao.utils.My_BaseAdapter;
import com.example.ywj.toutiao.utils.ResponseApi;
import com.example.ywj.toutiao.utils.SpUtils;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.hb.dialog.myDialog.MyImageMsgDialog;

import java.util.ArrayList;
import java.util.List;


public class MyFragment extends Fragment {
    private static final String TAG = "MyFragment";
    public View view;
    public TextView my_star,my_comment,my_good,my_clock,my_login,myfragment_next;
    public ListView listView1,listView2,listView3;
    public List<User> list;
    public ImageView my_avatar;
    public TextView my_nickname,my_desc;
    public String username;
    public TextView my_toutiao_count;
    public TextView my_guanzhu_count;
    public TextView my_fensi_count;
    public TextView my_dianzan_count;

    //public TextView my_login0ut;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(view == null){
            view = inflater.inflate(R.layout.my_fragment, null);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Window window = getActivity().getWindow();
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(Color.TRANSPARENT);
            }
            username = SpUtils.getString(view.getContext(),"username");
            SpUtils.putBoolean(view.getContext(),"isreturn",true);
            getUser(username);
            initView();
            if(!username.equals("")){
                myNewCount(username);
                myAttentionCount(username);
                myFensiCount(username);
                myhuozanCount(username);
            }
        }
        return view;
    }
    public void initView(){
        my_avatar = view.findViewById(R.id.my_avatar);
        my_nickname = view.findViewById(R.id.my_nickname);
        my_login = view.findViewById(R.id.my_login);
        my_desc = view.findViewById(R.id.my_desc);
        my_toutiao_count = view.findViewById(R.id.my_toutiao_count);
        my_guanzhu_count = view.findViewById(R.id.my_guanzhu_count);
        my_fensi_count = view.findViewById(R.id.my_fensi_count);
        my_dianzan_count = view.findViewById(R.id.my_dianzan_count);
        my_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(v.getContext(),LoginActivity.class);
                startActivity(intent);
            }
        });
        my_star = view.findViewById(R.id.my_star);
        my_comment = view.findViewById(R.id.my_comment);
        my_good = view.findViewById(R.id.my_good);
        my_clock = view.findViewById(R.id.my_clock);
        myfragment_next = view.findViewById(R.id.myfragment_next);
        Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "iconfont.ttf");
        my_star.setTypeface(font);
        my_star.setText(getResources().getString(R.string.star));
        my_star.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(v.getContext(),SaveListActivity.class);
                startActivity(intent);
            }
        });
        my_comment.setTypeface(font);
        my_comment.setText(getResources().getString(R.string.comment));
        my_comment.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(v.getContext(),CommentListActivity.class);
                startActivity(intent);
            }
        });
        my_good.setTypeface(font);
        my_good.setText(getResources().getString(R.string.good));
        my_good.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(v.getContext(),LikeListActivity.class);
                startActivity(intent);
            }
        });
        my_clock.setTypeface(font);
        my_clock.setText(getResources().getString(R.string.clock));
        myfragment_next.setTypeface(font);
        myfragment_next.setText(getResources().getString(R.string.go));
        listView1 = view.findViewById(R.id.listview1);
        listView2 = view.findViewById(R.id.listview2);
        listView3 = view.findViewById(R.id.listview3);
        RelativeLayout relativeLayout1 = view.findViewById(R.id.nousername);
        RelativeLayout relativeLayout2 = view.findViewById(R.id.haveusername);
        String username = SpUtils.getString(view.getContext(),"username");
        Log.i(TAG, "initView: "+username);
        if(!username.equals("")){
            Log.i(TAG, "initView: "+1);
            relativeLayout2.setVisibility(View.VISIBLE);
            relativeLayout1.setVisibility(View.GONE);
            //my_login0ut.setVisibility(View.VISIBLE);
        }else{
            Log.i(TAG, "initView: "+2);
            relativeLayout2.setVisibility(View.GONE);
            relativeLayout1.setVisibility(View.VISIBLE);
           // my_login0ut.setVisibility(View.GONE);
        }
        String titleArr1[] = {"我的关注","我的钱包","消息通知","小程序"};
        String extraArr1[] = {"","转盘福利大派送","",""};
        List<Item> list1 = new ArrayList<>();
        List<Item> list2 = new ArrayList<>();
        List<Item> list3 = new ArrayList<>();
        for(int i=0;i<titleArr1.length;i++){
           Item item = new Item(titleArr1[i],extraArr1[i]);
           list1.add(item);
       }
        My_BaseAdapter my_baseAdapter = new My_BaseAdapter(list1);
        listView1.setAdapter(my_baseAdapter);
        String titleArr2[] = {"扫一扫","免流量服务","阅读公益"};
        String extraArr2[] = {"","","今天阅读0分钟"};
        for(int j=0;j<titleArr2.length;j++){
            Item item = new Item(titleArr2[j],extraArr2[j]);
            list2.add(item);
        }
        My_BaseAdapter my_baseAdapter1 = new My_BaseAdapter(list2);
        listView2.setAdapter(my_baseAdapter1);
        String titleArr3[] = {"用户反馈","系统设置"};
        String extraArr3[] = {"",""};
        for(int z=0;z<titleArr3.length;z++){
            Item item = new Item(titleArr3[z],extraArr3[z]);
            list3.add(item);
        }
        My_BaseAdapter my_baseAdapter2 = new My_BaseAdapter(list3);
        listView3.setAdapter(my_baseAdapter2);
        setListViewHeightBasedOnChildren(listView1);
        setListViewHeightBasedOnChildren(listView2);
        setListViewHeightBasedOnChildren(listView3);
        relativeLayout2.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(v.getContext(),HomePageActivity.class);
                startActivity(intent);
                
            }
        });
        myfragment_next.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(v.getContext(),HomePageActivity.class);
                startActivity(intent);
            }
        });
    }
    public void getUser(String username){
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(Constant.BASEURL)
                .build();
        ResponseApi responseApi = retrofit.create(ResponseApi.class);
        Call<ResponseBody> call = responseApi.getInfoByUsername(username);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try{
                    json = response.body().string();
                }catch (Exception e){
                    e.printStackTrace();
                }
                JsonObject obj = (JsonObject)new JsonParser().parse(json);
                Integer code = obj.get("statusCode").getAsInt();
                if(code == 200 && obj.has("data")){
                    JsonArray objArr = obj.getAsJsonArray("data");
                    Gson gson = new Gson();
                    list = gson.fromJson(objArr,new TypeToken<ArrayList<User>>(){}.getType());
                    my_nickname.setText(list.get(0).getNickname());
                    String url = Constant.BASEURL+"public/images/"+list.get(0).getAvatar()+".jpg";
                    RequestOptions requestOptions = new RequestOptions();
                    requestOptions.placeholder(R.drawable.boy).error(R.drawable.error_img);
                    Glide.with(view.getContext()).load(url).apply(requestOptions).into(my_avatar);
                    my_desc.setText(list.get(0).getDesc());
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.i(TAG, "onFailure: "+t);
            }
        });
    }
    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }
    public void myNewCount(String username){
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(Constant.BASEURL)
                .build();
        ResponseApi responseApi = retrofit.create(ResponseApi.class);
        Call<ResponseBody> call = responseApi.myNewCount(username);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try{
                    json = response.body().string();
                }catch (Exception e){
                    e.printStackTrace();
                }
                Log.i(TAG, "onResponse: "+json);
                JsonObject obj = (JsonObject)new JsonParser().parse(json);
                Integer code = obj.get("statusCode").getAsInt();
                if(code == 200){
                    Integer count = obj.get("data").getAsInt();
                    Log.i(TAG, "onResponse: "+count);
                    my_toutiao_count.setText(count+"");
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.i(TAG, "onFailure: "+t);
            }
        });
    }

    public void myAttentionCount(String username){
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(Constant.BASEURL)
                .build();
        ResponseApi responseApi = retrofit.create(ResponseApi.class);
        Call<ResponseBody> call = responseApi.myAttentionCount(username);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try{
                    json = response.body().string();
                }catch (Exception e){
                    e.printStackTrace();
                }
                Log.i(TAG, "onResponse: "+json);
                JsonObject obj = (JsonObject)new JsonParser().parse(json);
                Integer code = obj.get("statusCode").getAsInt();
                if(code == 200){
                    Integer count = obj.get("data").getAsInt();
                    Log.i(TAG, "onResponse: "+count);
                    my_guanzhu_count.setText(count+"");
                    my_guanzhu_count.setOnClickListener(new View.OnClickListener(){
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(v.getContext(),Attention1Activity.class);
                            startActivity(intent);
                        }
                    });
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.i(TAG, "onFailure: "+t);
            }
        });
    }
    public void myFensiCount(String username){
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(Constant.BASEURL)
                .build();
        ResponseApi responseApi = retrofit.create(ResponseApi.class);
        Call<ResponseBody> call = responseApi.myFensiCount(username);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try{
                    json = response.body().string();
                }catch (Exception e){
                    e.printStackTrace();
                }
                Log.i(TAG, "onResponse: "+json);
                JsonObject obj = (JsonObject)new JsonParser().parse(json);
                Integer code = obj.get("statusCode").getAsInt();
                if(code == 200){
                    Integer count = obj.get("data").getAsInt();
                    Log.i(TAG, "onResponse: "+count);
                    my_fensi_count.setText(count+"");
                    my_fensi_count.setOnClickListener(new View.OnClickListener(){
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(v.getContext(),Attention2Activity.class);
                            startActivity(intent);
                        }
                    });
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.i(TAG, "onFailure: "+t);
            }
        });
    }
    public void myhuozanCount(String username){
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(Constant.BASEURL)
                .build();
        ResponseApi responseApi = retrofit.create(ResponseApi.class);
        Call<ResponseBody> call = responseApi.myhuozanCount(username);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try{
                    json = response.body().string();
                }catch (Exception e){
                    e.printStackTrace();
                }
                Log.i(TAG, "onResponse: 或i赞"+json);
                JsonObject obj = (JsonObject)new JsonParser().parse(json);
                Integer code = obj.get("statusCode").getAsInt();
                if(code == 200){
                    Integer count = obj.get("data").getAsInt();
                    Log.i(TAG, "onResponse: "+count);
                    my_dianzan_count.setText(count+"");
                    my_dianzan_count.setOnClickListener(new View.OnClickListener(){
                        @Override
                        public void onClick(View v) {
                            MyImageMsgDialog myImageMsgDialog = new MyImageMsgDialog(v.getContext()).builder()
                                    .setImageLogo(getResources().getDrawable(R.mipmap.ic_launcher))
                                    .setMsg("获得了"+my_dianzan_count.getText().toString()+"个赞");
                            ImageView logoImg = myImageMsgDialog.getLogoImg();
                            logoImg.setImageResource(R.drawable.good);
                            myImageMsgDialog.show();
                        }
                    });
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.i(TAG, "onFailure: "+t);
            }
        });
    }
}
